package com.yangli.leecode.b;

import com.yangli.ahies.study.util.ListNode;

/**
 * @author ly
 * @description
 * @data 2022/4/29
 */
public class RemoveNthFromEnd {
    public static void main(String[] args) {

        RemoveNthFromEnd removeNthFromEnd = new RemoveNthFromEnd();
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2, l1);
        ListNode l3 = new ListNode(3, l2);
        ListNode l4 = new ListNode(4, l3);
        ListNode l5 = new ListNode(5, l4);
        ListNode l6 = new ListNode(6, l5);

        System.out.println(removeNthFromEnd.removeNthFromEnd(l1, 1));
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode listNode = new ListNode(0);
        listNode.next = head;
        nodeNext(listNode, n);
        return listNode.next;
    }

    static int i = 0;

    public ListNode nodeNext(ListNode node, int n) {
        ListNode temp = node;
        while (node.next != null) {
            node = nodeNext(node.next, n);
        }
        ++i;
        if (i == n + 1) {
            temp.next = temp.next.next;
        }
        return node;
    }

    public ListNode removeNthFromEnd2(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = dummy.next;
        return ans;
    }




    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }

}
